/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: EmergencyStop_Dummy.cpp,v 1.2 2009-11-09 17:24:44 morsko Exp $
 *
 * \file
 * \brief Example implementation for EmergencyStop server module.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 *
 ******************************************************************************
 * NOTE: The following 'Module Info' should be kept up-to-date. Do NOT
 * change its format, insert your information according to the template.
 ******************************************************************************
 * Module Info:
 *
 * Uses drivers:
 * - none
 *
 * Provides Interfaces:
 * - EmergencyStop
 *
 * Needs Interfaces:
 * - none
 *
 * General information:
 * - This is a Dummy module for interface example purposes.
 * 
 ******************************************************************************
 */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "owndebug.h"
#include "ownutils.h"
#include "settings.hpp"
#include "binbag.h"
#include "EmergencyStopServer.hpp"

//*****************************************************************************

// Include GIMI in proper way
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************

// Set initial verbosity level to ODINFO
static int verbose = ODINFO;
//*****************************************************************************

// Choose your namespace
using namespace MaCI;
using namespace MaCI::EmergencyStop;
//*****************************************************************************

// Running?
static volatile bool run = true;
static ownThreadHandle signalHandlerThread;
//*****************************************************************************

// GIMnet parameters
static std::string gimnetAP = "asrobo.hut.fi";
static int gimnetAPPort = 50002;
static std::string gimnetName;
static std::string macigroup;
// Configuration parameters
static std::string configurationFile;
//*****************************************************************************


static int SignalHandlerThread(void *)
{
  dPrint(8, "Signal handler thread (%ld) starting...", pthread_self());

  while (run) {
    // Now, wait for requested signals to arrive
    int sig;
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGTERM);
    sigaddset(&mask, SIGPIPE);
    sigaddset(&mask, SIGHUP);
    sigwait(&mask, &sig);

    // Got signal, sigwait returned!
    dPrint(ODSTATUS,"Got Signal '%d' (%s)", sig, strsignal(sig));

    // What to do?
    switch(sig) {
    case SIGINT:
    case SIGTERM:
    case SIGPIPE:
    case SIGHUP:
      run = false;
      ownSleep_ms(1000);
      break;
      
    default:
      dPrint(ODSTATUS,"Unhandled signal! Ignore!");
      break;
    }
  }
  return 0;
}
//****************************************************************************

static void InitSignalHandler(void)
{
  // Now; Set to BLOCK ALL SIGNALS
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGINT);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGPIPE);
  sigaddset(&mask, SIGHUP);
  pthread_sigmask(SIG_BLOCK, &mask, NULL);
  
  // Start signal handler thread
  signalHandlerThread = ownThread_Create((void*)SignalHandlerThread, NULL);
}
//*****************************************************************************
//*****************************************************************************

/**
 * All MaCI modules should support these parameters with exactly these names
 * *** DO NOT CHANGE NOR DELETE ANY OF THEM ***
 * Howevery, feel free to add new parameters as you wish.
 */
static void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tSQLSQL [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-f conf_file]\t\tUse 'conf_file' as configuration file for this module\n");
  fprintf(stderr,"  [-G name]\t\t\tSpecify the MaCIGroup for this module\n");
  
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*************************************************************************

static int dummyWatch(CEmergencyStopServer *ess)
{
  CEmergencyStopData esd;
  EMaCIError e;
  SMessageSource src;
  bool emergencyStopActivated = false;
  dPrint(1,"Dummy watch started");
  while(run) {
    e = ess->WaitCommand(esd, src, 1000,false);
    if (e == KMaCIOK) {
      const TCommand *c = esd.GetCommand();
      if (c) {
        dPrint(2,"Got command: %d", c->cmd);
        switch(c->cmd) {
        case  KCommandActivateEmergencyStop:{
          dPrint(1,"Got command ACTIVATE EMERGENCY STOP!");
          emergencyStopActivated = true;
          //Then send the same message as reply to the client,
          //It's to be sure that the message has actually reached the server side.
          ess->SendReply(esd,src);
          break;
        }
        case KCommandDeactivateEmergencyStop:{
          dPrint(1,"Got command DEACTIVATE EMERGENCY STOP!");
          emergencyStopActivated = false;
          //Then send the same message as reply to the client,
          //It's to be sure that the message has actually reached the server side.
          ess->SendReply(esd,src);
          break;
        }
        case KCommandNoActiveClients:{
          if(!emergencyStopActivated){
            dPrint(1,"Got command NO ACTIVE CLIENTS! Activating emergencystop");
            emergencyStopActivated = true;

          }
          break;
        }
        default:
          dPrint(ODINFO,"Unidentified command for emergencyStop dummy '%d'",c->cmd);
          break;
        }
      }else{
        dPrint(ODERROR,"Got Command, but no Command element present???");

      }
    }
    //Then send status of emergencyStop module
    CEmergencyStopData status;
    status.CreateInternalBinBag();
    status.SetCommand(KCommandStatusEvent);
    if(emergencyStopActivated){
      status.SetEmergencyStopStatus(TStatus(KStatusEmergencyStopActivated));
    }else{
      status.SetEmergencyStopStatus(TStatus(KStatusEmergencyStopDeactivated));
    }
    ess->SendEmergencyStopEvent(status);
  }

  return 0;
}
//*************************************************************************
static int ExecuteModule(gimi::GIMI &g)
{
  // Construct an MaCICtrlServer instance
  MaCICtrl::CMaCICtrlServer mcs(&g, 0);

  // Construct instance of SQLServer
  CEmergencyStopServer ess(&mcs, 0, "EmergencyStop dummy service");

  // Construct instance of EmergencyStopData && Init to use internal BinBag
  CEmergencyStopData esd;
  esd.CreateInternalBinBag();


  // Set GroupName for MaCICtrlServer and Instance for EmergencyStopServer.
  mcs.SetGroupName(macigroup);
  ess.SetInterfaceInstanceName("Dummy");
  // Create command watch.
  ownThreadHandle dummyWatchThread;
  ess.SetTimeoutTime(500,
                     MaCI::Common::TTimestamp(10,0)); ///< 10 s.

  if (ess.Open() == KMaCIOK) {
    // Run!
    dummyWatchThread = ownThread_Create((void*)dummyWatch, &ess);
    // At this point, we have a preconnected GIMI, so now its up to you
    // to do things.  For more examples of functionality and structure,
    // see other MaCI modules, such as Alarm_SQL.cpp.
    while(run) {
      
      ownSleep_ms(1000);
    }

    // Add a call to gimi:stop()
    g.stop();

    // wait until the command handling thread terminates.
    ownThread_Join(dummyWatchThread, NULL);

  } else {
    dPrint(ODERROR,"Failed to open CEmergencyStopServer instance! Fatal error.");
    return -1;

  }
  

  return 0;

}
//*****************************************************************************

int main(int argc, char *argv[]) 
{
  // setup signal handling
  InitSignalHandler();

  // Objects
  gimi::GIMI g;

  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(verbose);
  const std::string logfile = std::string(argv[0]) + ".log";
  debugSetLogFilename(logfile.c_str());

  // Greet
  fprintf(stderr,
	  "\n%s - $Revision: 1.2 $\n", argv[0]);

  /////////////////////////////////////////////////////////////////////////////
  // Parse parameters - Remember: ** DO NOT MODIFY OR DELETE ANY OF THIS **
  // _Add_ anything as you wish.
  ///////////////////////////////////////////////////////////////////////////// 
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "f:n:u:p:G:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////////////////////////////////////////////
      /// Add here anything you need.
      /////////////////////////////////////////////////////////////////////////

      /////////////////////////////////
      ///// MaCI/GIMnet parameters ////
      /////////////////////////////////
    case 'f':
      configurationFile = optarg;
      dPrint(ODVINFO,"Using configuration file: '%s'", optarg);
     
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(ODVINFO,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(ODVINFO,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(ODVINFO,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

    case 'G':
      macigroup = optarg;
      dPrint(ODVINFO,"Using MaCI-Group '%s'", optarg);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }
  
  /////////////////////////////////////////////////////////////////////////////
  // Execute connection to GIMnet.
  /////////////////////////////////////////////////////////////////////////////
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(ODERROR,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(ODINFO,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
    // GIMnet connection OK, now execute module.
    r = ExecuteModule(g);
  }

  return 0;
}

